package cashe;
import static org.junit.Assert.assertEquals;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Before;
import org.junit.Test;

import testharness.ConcurrentHarness;

public class TestUnsafeCache extends ConcurrentHarness {

	private UnsafeCache<Integer, Integer> cache;
	AtomicInteger HitCache = new AtomicInteger(0);
	AtomicInteger BrokeCache = new AtomicInteger(0);

	@Before
	public void initCounter() {
		cache = new UnsafeCache<>();
	}

	@Test
	public void testAtomicCounter() {
		submitTasks();
	}

	@Override
	protected Runnable newTask() {
		return new Runnable() {
			@Override
			public void run() {
				try {
					Integer i = (int) (50 * Math.random());
					Integer iFromCache = cache.get(i);
					if (iFromCache != null) {
						HitCache.incrementAndGet();
						if (!i.equals(iFromCache))
							BrokeCache.incrementAndGet();
					} else {
						cache.put(i, i);
					}
					;
				} catch (Exception e) {
					System.out.println(e.getStackTrace());
				}

			}
		};
	}

	public void checkResults() {
		System.out.println("HitCache=" + HitCache);
		System.out.println("BrokeCache=" + BrokeCache);
		assertEquals(0, BrokeCache.get());
	}

}
